package com.icez.verification_code_input_view

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.text.InputType
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout


/**
 * 验证码输入框
 * @sample
 * @author Icez
 */
class VerificationCodeInputView @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    // 子控件数量
    private var mChildViewCount: Int = 0

    // 子控件宽度
    private var mChildViewWidth: Int = 0

    // 子控件的高度
    private var mChildViewHeight: Int = 0

    // 子控件的垂直外补丁
    private var mChildViewVerticalMargin = 0

    // 子控件的水平外补丁
    private var mChildViewHorizontalMargin = 0

    // 验证码类型
    private var mInputType: Int = VerificationCodeInputType.NUMBER_PASSWORD.ordinal

    // 选中的子控件背景
    private var mChildViewSelectedBg:Drawable ?= null

    // 没有选中的子控件背景
    private var mChildViewNormalBg:Drawable ?= null

    // 已填写的背景
    private var mChildViewFillBg:Drawable ?= null

    // 文本颜色
    private var mChildViewTextColor:Int = 0

    // 验证码子控件样式
    var mVerificationCodeInputChildStyleListener: VerificationCodeInputChildStyleListener? =
        null

    // 子控件文本监听
    private var mChildViewTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

        override fun afterTextChanged(p0: Editable?) {
            if (!p0.isNullOrEmpty()) {
                setChildFocus()
                checkInputComplete()
            }
        }
    }

    private var mVerificationCodeDelListener = object :
        VerificationCodeEditText.VerificationCodeDelListener {
        override fun onDelSoftListener() {
            setBackFocus()
        }

    }

    /**
     *  打开软键盘
     * @param view
     */
    public fun openSoftKeyboard(view: View?) {
        postDelayed({view?.isFocusableInTouchMode = true
            view?.setFocusable(true)
            view?.requestFocus()
            val imm =
                view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)},100)
    }





    init {
        orientation = HORIZONTAL
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.VerificationCodeInputView)
        mChildViewCount =
            typeArray.getInteger(R.styleable.VerificationCodeInputView_childViewCount, 6)
        mChildViewWidth = typeArray.getDimensionPixelSize(
            R.styleable.VerificationCodeInputView_childViewWidth,
            120
        )
        mChildViewSelectedBg = typeArray.getDrawable(R.styleable.VerificationCodeInputView_childViewSelectedBg)
        mChildViewNormalBg = typeArray.getDrawable(R.styleable.VerificationCodeInputView_childViewNormalBg)
        mChildViewFillBg = typeArray.getDrawable(R.styleable.VerificationCodeInputView_childViewFilledBg)
        mChildViewHeight = typeArray.getDimensionPixelSize(
            R.styleable.VerificationCodeInputView_childViewHeight,
            120
        )
        mChildViewVerticalMargin = typeArray.getDimensionPixelSize(
            R.styleable.VerificationCodeInputView_childViewVerticalMargin,
            14
        )
        mChildViewHorizontalMargin = typeArray.getDimensionPixelSize(
            R.styleable.VerificationCodeInputView_childViewHorizontalMargin,
            14
        )
        mInputType = typeArray.getInteger(
            R.styleable.VerificationCodeInputView_inputType,
            VerificationCodeInputType.NUMBER_PASSWORD.ordinal
        )
        mChildViewTextColor = typeArray.getColor(
            R.styleable.VerificationCodeInputView_childViewTextColor,
            0
        )
        typeArray.recycle()
        addChildView()
    }


    /**
     * 添加子控件
     * @sample
     * @author Icez
     */
    private fun addChildView() {
        for (i in 0 until mChildViewCount) {
            val childView = VerificationCodeEditText(context)
            val childLayoutParams = LayoutParams(mChildViewWidth, mChildViewHeight)
            childLayoutParams.bottomMargin = mChildViewVerticalMargin
            childLayoutParams.topMargin = mChildViewVerticalMargin
            childLayoutParams.leftMargin = mChildViewHorizontalMargin
            childLayoutParams.rightMargin = mChildViewHorizontalMargin
            childLayoutParams.gravity = Gravity.CENTER

            if (mChildViewTextColor != 0) {
                childView.setTextColor(mChildViewTextColor)
            }

            childView.mVerificationCodeDelListener = mVerificationCodeDelListener
            childView.layoutParams = childLayoutParams
            childView.gravity = Gravity.CENTER
            //设置过滤，长度过滤
            childView.filters = arrayOf<InputFilter>(LengthFilter(1))



            when (mInputType) {
                VerificationCodeInputType.PHONE.ordinal -> {
                    childView.inputType = InputType.TYPE_CLASS_PHONE
                }
                VerificationCodeInputType.NUMBER.ordinal -> {
                    childView.inputType = InputType.TYPE_CLASS_NUMBER
                }
                VerificationCodeInputType.NUMBER_PASSWORD.ordinal -> {
                    childView.inputType =
                        InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
                }
                VerificationCodeInputType.TEXT_PASSWORD.ordinal -> {
                    childView.inputType =
                        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                }
                VerificationCodeInputType.TEXT.ordinal -> {
                    childView.inputType = InputType.TYPE_CLASS_TEXT
                }
            }

            childView.setEms(1)
            childView.addTextChangedListener(mChildViewTextWatcher)

            if(mChildViewNormalBg!=null){
                childView.background = mChildViewNormalBg
            }

            mVerificationCodeInputChildStyleListener?.normalStyle(childView, i)

            addView(childView)

        }

        setChildFocus()
        openSoftKeyboard( getChildAt(0) as EditText)

    }

    /**
     * 设置返回子控件焦点
     * @sample
     * @author Icez
     */
    private fun setBackFocus() {
        for (i in (childCount - 1) downTo 0) {
            val childView = getChildAt(i) as VerificationCodeEditText
            if (childView.text.length == 1) {
                childView.requestFocus()
                childView.setSelection(1)
                if(mChildViewSelectedBg!=null){
                    childView.background = mChildViewSelectedBg
                }
                mVerificationCodeInputChildStyleListener?.selectdStyle(childView, i)
                return
            }else {
                if (mChildViewNormalBg != null) {
                    childView.background = mChildViewNormalBg
                }
                mVerificationCodeInputChildStyleListener?.normalStyle(childView, i)
            }
        }
    }

    /**
     * 检查输入完成
     * @sample
     * @author Icez
     */
    private fun checkInputComplete() {
        //所有的密码
        val allPassword = StringBuilder()
        //是否填写完
        var isInputComplete = true
        for (i in 0 until mChildViewCount) {
            val childView = getChildAt(i) as VerificationCodeEditText
            val password = childView.text
            if (password.isEmpty()) {
                isInputComplete = false
                break
            } else {
                allPassword.append(password)
            }
        }
        if (isInputComplete) {
            //全部填完监听
            mVerificationCodeInputChildStyleListener?.complete(allPassword.toString())
            isEnabled = false
        }
    }

    /**
     * 设置子控件焦点
     * @sample
     * @author Icez
     */
    private fun setChildFocus() {
        for (i in 0 until childCount) {
            val childView = getChildAt(i) as VerificationCodeEditText
            if (childView.text.isEmpty()) {
                childView.requestFocus()
                if(mChildViewSelectedBg!=null){
                    childView.background = mChildViewSelectedBg
                }
                mVerificationCodeInputChildStyleListener?.selectdStyle(childView, i)
                return
            }else{
                if (mChildViewFillBg != null) {
                    childView.background = mChildViewFillBg
                } else {
                    if (mChildViewNormalBg != null) {
                        childView.background = mChildViewNormalBg
                    }
                }
                mVerificationCodeInputChildStyleListener?.normalStyle(childView, i)
            }
        }
    }

    interface VerificationCodeInputChildStyleListener {
        fun selectdStyle(editText: VerificationCodeEditText, position: Int)

        fun normalStyle(editText: VerificationCodeEditText, position: Int)

        fun complete(password: String)
    }

    enum class VerificationCodeInputType {
        NUMBER,
        TEXT,
        NUMBER_PASSWORD,
        TEXT_PASSWORD,
        PHONE
    }
}